package com.example.houduan.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.houduan.entity.AliPayConfig;
import com.example.houduan.utils.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import static com.example.houduan.entity.AliPayConfig.*;

/**
 * @program: huda2025-6-20
 * @description:
 * @author: DY
 * @create: 2025-06-28 10:35
 **/
@RestController
public class PayController {

    @GetMapping(value = "/doPay")
    public Result pay(@RequestParam Integer total, @RequestParam String subject, HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, AliPayConfig.appId,
                AliPayConfig.appPrivateKey, FORMAT, CHARSET, AliPayConfig.alipayPublicKey, SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        //request.setNotifyUrl(AliPayConfig.notifyUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", UUID.randomUUID().toString());  // 我们自己生成的订单编号
        bizContent.put("total_amount", total); // 订单的总金额
        bizContent.put("subject", subject);   // 支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl(AliPayConfig.returnUrl); // 支付完成后自动跳转到本地页面的路径
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.success(form);
    }
}
